<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('menu.menuItemInfo')"
    custom-class="dialog-min-width"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formEdit" :rules="rules" label-width="120px">
      <el-row>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('menu.paths')">
            <el-cascader
              v-if="state.dialogFormVisible"
              :props="menuProps"
              show-all-levels
              clearable
              class="fix-el-cascader-width-100"
              v-model="formEdit.menuPaths"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('menu.resourcePaths')">
            <el-cascader
              v-if="state.dialogFormVisible"
              ref="resourceRef"
              :props="resourceProps"
              show-all-levels
              clearable
              class="fix-el-cascader-width-100"
              @change="onResourceCascaderChange"
              v-model="formEdit.resourcePaths"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('menu.menuItemCnName')" prop="menuItemCnName">
            <el-input
              v-model="formEdit.menuItemCnName"
              maxlength="64"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('menu.menuItemEnName')">
            <el-input
              v-model="formEdit.menuItemEnName"
              maxlength="64"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item prop="levelCode">
            <template #label>
              {{ t("menu.levelCode") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('menu.levelCodeContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-input v-model="formEdit.levelCode" maxlength="64" clearable>
              </el-input
            ></template>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('menu.icon')">
            <el-input v-model="formEdit.icon" clearable> </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item>
            <template #label>
              {{ t("menu.isVisible") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('menu.isVisibleContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-switch
                v-model="formEdit.visible"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24"></el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('menu.description')">
            <el-input
              v-model="formEdit.description"
              maxlength="64"
              type="textarea"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { Warning } from "@element-plus/icons-vue";
import utils from "../../../../utils/utils";
import apiMenu from "../../api/menu";
import MenuItemTreeNode from "./tree-node";
import apiResource from "../../api/resource";
import ResourceTreeNode from "../../resource/tree-node";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const formRef = ref();
const resourceRef = ref();

const formEditOriginal = () => {
  return {
    menuItemId: "",
    parentId: "",
    menuId: "",
    resourceId: "",
    levelCode: "",
    menuItemCnName: "",
    menuItemEnName: "",
    icon: "",
    visible: 1,
    hasChildren: 0,
    // 提交数据库，逗号分隔字符串
    menuPath: "",
    // 前台临时使用，绑定下拉树
    menuPaths: <any>null,
    resourcePath: "",
    // 可以触发空值时的表单验证
    resourcePaths: <any>null,
    description: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  resourcePaths: [
    {
      required: true,
      message: () => t("common.select"),
      trigger: "change",
    },
  ],
  menuItemCnName: [
    { required: true, message: () => t("common.required"), trigger: "blur" },
  ],
  levelCode: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
});

const state = reactive({
  dialogFormVisible: false,
});

const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const menuProps = {
  label: "menuItemCnName",
  value: "menuItemId",
  leaf: "leaf",
  checkStrictly: true,
  lazy: true,
  async lazyLoad(node: any, resolve: any) {
    if (node.level === 0) {
      let childs = await apiMenu.loadChilds("0");
      let nodes = Array<MenuItemTreeNode>();
      Object.assign(nodes, childs);
      return resolve(nodes);
    } else {
      if (node.data.leaf) {
        resolve([]);
      }
      let childs = await apiMenu.loadChilds(node.data.menuItemId);
      let nodes = Array<MenuItemTreeNode>();
      Object.assign(nodes, childs);
      return resolve(nodes);
    }
  },
};

const resourceProps = {
  label: "resourceName",
  value: "resourceId",
  leaf: "leaf",
  checkStrictly: true,
  lazy: true,
  async lazyLoad(node: any, resolve: any) {
    if (node.level === 0) {
      let childs = await apiResource.loadChilds("0");
      let nodes = Array<ResourceTreeNode>();
      Object.assign(nodes, childs);
      return resolve(nodes);
    } else {
      if (node.data.leaf) {
        resolve([]);
      }
      let childs = await apiResource.loadChilds(node.data.resourceId);
      let nodes = Array<ResourceTreeNode>();
      Object.assign(nodes, childs);
      return resolve(nodes);
    }
  },
};

const onResourceCascaderChange = (value: any) => {
  // 单选情况下获取选中数据，value 仅对应 prop 中的 value 即 menuItemId，信息有限
  // console.log("onResourceCascaderChange", orgRef.value.getCheckedNodes()[0].data);
  if (
    formEdit.menuItemCnName == "" &&
    resourceRef.value.getCheckedNodes() != undefined
  ) {
    formEdit.menuItemCnName =
      resourceRef.value.getCheckedNodes()[0].data.resourceName;
    formRef.value.validate();
    // 重置表单校验
    // setTimeout(() => {
    //   if (formRef.value) {
    //     formRef.value.resetFields();
    //   }
    // }, 100);
  }
};

const handleSubmit = async () => {
  // 处理业务逻辑，触发关闭事件
  // console.log("formEdit.menuPaths", formEdit.menuPaths);
  // console.log("formEdit.resourcePaths", formEdit.resourcePaths);
  await formRef.value.validate();

  formEdit.parentId = "";
  if (formEdit.menuPaths != null && formEdit.menuPaths.length > 0) {
    formEdit.parentId = formEdit.menuPaths[formEdit.menuPaths.length - 1];
    formEdit.menuPath = formEdit.menuPaths.join(",");
  } else {
    formEdit.parentId = "";
    formEdit.menuPath = "";
  }

  formEdit.resourceId = "";
  if (formEdit.resourcePaths != null && formEdit.resourcePaths.length > 0) {
    formEdit.resourceId =
      formEdit.resourcePaths[formEdit.resourcePaths.length - 1];
    formEdit.resourcePath = formEdit.resourcePaths.join(",");
  } else {
    // 可以触发空值时的表单验证
    formEdit.resourcePaths = <any>null;
  }

  apiMenu
    .updateMenuItem(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (menuId: string, row: any) => {
  console.log("menuId", menuId);
  Object.assign(formEdit, formEditOriginal());
  // 新增情况赋值
  formEdit.menuId = menuId;
  if (row != undefined) {
    apiMenu
      .getMenuItem(row.menuItemId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
          // 修改情况赋值
          formEdit.menuId = menuId;
          if (formEdit.menuPath.length > 0) {
            formEdit.menuPaths = formEdit.menuPath.split(",");
          }
          if (formEdit.resourcePath.length > 0) {
            formEdit.resourcePaths = formEdit.resourcePath.split(",");
          }
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }
  // 触发刷新树
  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

defineExpose({
  show,
});
</script>
